package fr.aracore.domotique.zapi.core;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import fr.aracore.domotique.zapi.event.ZbEvent;
import fr.aracore.domotique.zapi.event.ZbEventHandler;

public class ZbEventListener implements Runnable {
	
	public static final int LISTENER_PORT = 3500;
	private boolean run;
	
	public void run() {
		DatagramSocket socket;
		try {
			run=true;
			socket = new DatagramSocket(LISTENER_PORT);
			while (run) {
				byte[]ackByte=new byte[512];
				DatagramPacket packet=new DatagramPacket(ackByte, 512);
				try {
					socket.receive(packet);
					ZbResponse response=new ZbResponse(packet.getData());
					System.out.println("Received response :"+response.message);
					ZbEvent lcEvent=new ZbEvent(response);
					lcEvent.addObserver(ZbEventHandler.eventHandler());
					lcEvent.notifyObservers();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			socket.close();
		} catch (SocketException e1) {
			e1.printStackTrace();
		}
	}
	
	public void stopListener(){
		run=false;
	}
}
